﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Umi.Web.Abstraction.Services;
using Umi.Web.Metadatas.Attributes;
using Umi.Web.Metadatas.Configurations;

namespace Umi.Web.Service.Services
{
    /// <summary>
    /// 消息发送
    /// </summary>
    [Service("EmailSender", Scoped = ServiceScoped.Single)]
    public class EmailMessageSender : IMessageSender
    {
        private readonly EmailSmtpServerConfiguration smtpServerConfiguration;

        private readonly SmtpClient smtp;

        public EmailMessageSender(IOptions<EmailSmtpServerConfiguration> options)
        {
            smtpServerConfiguration = options.Value;
            smtp = new SmtpClient(smtpServerConfiguration.SmtpServer, smtpServerConfiguration.SmtpPort)
            {
                Credentials = new NetworkCredential(smtpServerConfiguration.Account, smtpServerConfiguration.Password),
                EnableSsl = smtpServerConfiguration.UseSSL
            };
        }

        public async Task<bool> SendMessage(string recipient, string title, string context)
        {
            var sender = new MailAddress(smtpServerConfiguration.From, smtpServerConfiguration.Alias);
            using (MailMessage message = new MailMessage()
            {
                From = sender,
                Sender = sender,
                Subject = title,
                Body = context,
                IsBodyHtml = true,
                SubjectEncoding = Encoding.UTF8,
                BodyEncoding = Encoding.UTF8
            })
            {
                message.To.Add(recipient);
                await smtp.SendMailAsync(message);
                return true;
            }

        }
    }
}
